package com.baizhi.repository.impl;

import com.baizhi.entity.Emp;
import com.baizhi.repository.EmpEsRepository;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Repository
public class EmpEsRepositoryImpl implements EmpEsRepository {
    @Autowired
    private TransportClient client;
    @Override
    public List<Emp> selectByContent(String content) {
        //高亮查询
        SearchResponse searchResponse = client.prepareSearch("ems").setTypes("emp")
                .setQuery(QueryBuilders.multiMatchQuery(content, "content"))
                .highlighter(new HighlightBuilder().field("content").preTags("<span style='color:red'>").postTags("</span>"))
                .get();
        SearchHits hits = searchResponse.getHits();
        List<Emp> empList=new ArrayList<>();
        for(SearchHit hit:hits){
            String empJson = hit.getSourceAsString();
            ObjectMapper mapper=new ObjectMapper();
            Emp emp = null;

            try {
                //获取一般字段的数据，content字段没有高亮显示
                emp = mapper.readValue(empJson, Emp.class);
            } catch (IOException e) {
                e.printStackTrace();
            }
            String idStr = hit.getId();
            emp.setId(Integer.parseInt(idStr));
            //获取高亮字段
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            HighlightField field = highlightFields.get("content");
            Text text = field.fragments()[0];
            emp.setContent(text.string());
            empList.add(emp);
        }
        return empList;
    }

    @Override
    public void insert(Emp emp) {
        Map map=new HashMap();
        map.put("name",emp.getName());
        map.put("age",emp.getAge());
        map.put("content",emp.getContent());
        map.put("address",emp.getAddress());
        map.put("bir",emp.getBir());
        client.prepareIndex("ems", "emp", emp.getId()+"").setSource(map).get();
    }
}
